#include "downloadfile.h"

#include <QDebug>
#include <QDir>
#include <QDesktopServices>
#include <QNetworkRequest>
#include <QNetworkReply>

DownloadFile::DownloadFile(QObject *parent)
    :QObject(parent)
{
    m_status = Null;
}

DownloadFile::Status DownloadFile::status() const
{
    return m_status;
}

QString DownloadFile::file() const
{
    return m_fileName;
}

bool DownloadFile::checkFile(QString fileName)
{
    QString home = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    QDir dir(home);
    dir.mkpath(dir.absoluteFilePath("NumismatMobile"));
    dir.cd("NumismatMobile");
    return dir.exists(fileName);
}

void DownloadFile::downloadFile(QUrl url, QString fileName)
{
    QString home = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
    QDir dir(home);
    dir.mkpath(dir.absoluteFilePath("NumismatMobile"));
    dir.cd("NumismatMobile");
    m_fileName = dir.absoluteFilePath(fileName);

    m_file.setFileName(m_fileName);
    if (m_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(fileIsReady(QNetworkReply*)));
        manager.get(QNetworkRequest(url));

        m_status = Loading;
    }
    else {
        m_error = m_file.errorString();
        m_status = Error;
    }
    emit statusChanged(m_status);
}

QString DownloadFile::errorString()
{
    return m_error;
}

void DownloadFile::fileIsReady( QNetworkReply * preply)
{
    if (preply->error()) {
        m_error = preply->errorString();
        m_status = Error;
        m_file.remove();
    }
    else {
        m_file.write(preply->readAll());
        m_file.close();

        emit ready(m_fileName);
        m_status = Ready;
    }
    emit statusChanged(m_status);
    preply->deleteLater();
}
